#include <string>
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <cstring>
 #include <arpa/inet.h>
 #include <iostream>
using namespace std;

class UdpServer
{
public:
    UdpServer(int port)
    :_port(port)
    {
        _sockfd= socket(AF_INET, SOCK_DGRAM, 0);

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family= AF_INET;
        local.sin_port= htons(_port);
        local.sin_addr.s_addr= INADDR_ANY;

        bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
    }

    void Start()
    {
        char buffer[1024];
        while(1)
        {
            struct sockaddr_in peer;
            socklen_t len= sizeof(peer);
            int n= recvfrom(_sockfd, buffer, sizeof(buffer)-1 , 0,(struct sockaddr*)&peer, &len);
            if(n> 0)
            {
                buffer[n]= 0;
                cout<< "收到消息："<<buffer<<endl;

                sendto(_sockfd, buffer, n, 0, (struct sockaddr*)&peer, sizeof(peer));
            }
        }
    }

private:
    int _port;
    int _sockfd;

};



int main()
{
    UdpServer server(8888);
    server.Start();

    return 0;
}